/*
 * \brief  Generic IPC infrastructure
 * \author Norman Feske
 * \date   2006-06-12
 *
 * Most of the marshalling and unmarshallung code is generic for IPC
 * implementations among different platforms. In addition to the generic
 * marshalling items, platform-specific marshalling items can be realized
 * via specialized stream operators defined in the platform-specific
 * 'base/ipc.h'.  Hence, this header file is never to be included directly.
 * It should only be included by a platform-specific 'base/ipc.h' file.
 */

/*
 * Copyright (C) 2006-2009 Norman Feske
 * Genode Labs, Feske & Helmuth Systementwicklung GbR
 *
 * This file is part of the Genode OS framework, which is distributed
 * under the terms of the GNU General Public License version 2.
 */

#ifndef _INCLUDE__BASE__IPC_GENERIC_H_
#define _INCLUDE__BASE__IPC_GENERIC_H_

#include <util/misc_math.h>
#include <util/string.h>

#include <base/errno.h>
#include <base/exception.h>
#include <base/capability.h>
#include <base/ipc_msgbuf.h>

namespace Genode {

	enum Ipc_ostream_send      { IPC_SEND };
	enum Ipc_istream_wait      { IPC_WAIT };
	enum Ipc_client_call       { IPC_CALL };
	enum Ipc_server_reply_wait { IPC_REPLY_WAIT };


	/*********************
	 ** Exception types **
	 *********************/

	class Ipc_error : public Exception { };


	class Buffer
	{
		private:

			const char *_addr;
			size_t      _size;

		public:

			/**
			 * Construct buffer
			 */
			Buffer(const char *addr, size_t size)
			: _addr(addr), _size(size) { }

			/**
			 * Construct buffer from null-terminated string
			 */
			explicit Buffer(const char *str)
			: _addr(str), _size(strlen(str) + 1) { }

			/**
			 * Construct an invalid buffer as default
			 */
			Buffer(): _addr(0), _size(0) { }

			const char *addr() { return _addr; }
			size_t      size() { return _size; }
	};


	/**
	 * Marshal arguments into send message buffer
	 */
	class Ipc_marshaller
	{
		protected:

			char        *_sndbuf;
			size_t       _sndbuf_size;
			unsigned     _write_offset;

		protected:

			/**
			 * Write value to send buffer
			 */
			template <typename T>
			void _write_to_buf(T &value)
			{
				/* check buffer range */
				if (_write_offset + sizeof(T) >= _sndbuf_size) return;

				/* write integer to buffer */
				*reinterpret_cast<T *>(&_sndbuf[_write_offset]) = value;

				/* increment write pointer to next dword-aligned value */
				_write_offset += align_32bit(sizeof(T));
			}

			/**
			 * Write bytes to send buffer
			 */
			void _write_to_buf(const char *src_addr, unsigned num_bytes)
			{
				/* check buffer range */
				if (_write_offset + num_bytes >= _sndbuf_size) return;

				/* copy buffer */
				memcpy(&_sndbuf[_write_offset], src_addr, num_bytes);

				/* increment write pointer to next dword-aligned value */
				_write_offset += align_32bit(num_bytes);
			}

			/**
			 * Write Buffer to send buffer
			 */
			void _write_buffer_to_buf(Buffer b)
			{
				size_t size = b.size();
				_write_to_buf(size);
				_write_to_buf(b.addr(), size);
			}

		public:

			Ipc_marshaller(char *sndbuf, size_t sndbuf_size)
			: _sndbuf(sndbuf), _sndbuf_size(sndbuf_size), _write_offset(0) { }
	};


	/**
	 * Unmarshal arguments from receive buffer
	 */
	class Ipc_unmarshaller
	{
		protected:

			char        *_rcvbuf;
			size_t       _rcvbuf_size;
			unsigned     _read_offset;

		protected:

			/**
			 * Read value of type T from buffer
			 */
			template <typename T>
			void _read_from_buf(T &value)
			{
				/* check receive buffer range */
				if (_read_offset + sizeof(T) >= _rcvbuf_size) return;

				/* return value from receive buffer */
				value = *reinterpret_cast<T *>(&_rcvbuf[_read_offset]);

				/* increment read pointer to next dword-aligned value */
				_read_offset += align_32bit(sizeof(T));
			}

			/**
			 * Read Buffer from receive buffer
			 */
			void _read_bytebuf_from_buf(Buffer &b)
			{
				size_t size = 0;
				_read_from_buf(size);
				b = Buffer(0, 0);

				/* check receive buffer range */
				if (_read_offset + size >= _rcvbuf_size) return;

				b = Buffer(&_rcvbuf[_read_offset], size);
				_read_offset += align_32bit(size);
			}

			/**
			 * Read long value at specified byte index of receive buffer
			 */
			long _long_at_idx(int idx) { return *(long *)(&_rcvbuf[idx]); }

		public:

			Ipc_unmarshaller(char *rcvbuf, size_t rcvbuf_size)
			: _rcvbuf(rcvbuf), _rcvbuf_size(rcvbuf_size), _read_offset(0) { }
	};


	/**
	 * Stream for sending information via a capability to an endpoint
	 */
	class Ipc_ostream : public Ipc_marshaller
	{
		protected:

			Msgbuf_base *_snd_msg;  /* send message buffer */
			Capability   _dst;

			/**
			 * Reset marshaller and write badge at the beginning of the message
			 */
			void _prepare_next_send();

			/**
			 * Send message in _snd_msg to _dst
			 */
			void _send();

		public:

			/**
			 * Constructor
			 */
			Ipc_ostream(Capability dst, Msgbuf_base *snd_msg);

			/**
			 * Return true if Ipc_ostream is ready for send
			 */
			bool ready_for_send() { return _dst.valid(); }

			/**
			 * Insert value into send buffer
			 */
			template <typename T>
			Ipc_ostream &operator << (T value)
			{
				_write_to_buf(value);
				return *this;
			}

			/**
			 * Insert byte buffer to send buffer
			 */
			Ipc_ostream &operator << (Buffer b)
			{
				_write_buffer_to_buf(b);
				return *this;
			}

			/**
			 * Issue the sending of the message buffer
			 */
			Ipc_ostream &operator << (Ipc_ostream_send)
			{
				_send();
				return *this;
			}
	};


	/**
	 * Stream for receiving information
	 */
	class Ipc_istream : public Ipc_unmarshaller, public Capability
	{
		protected:

			Msgbuf_base      *_rcv_msg;
			Connection_state  _rcv_cs;

		protected:

			/**
			 * Reset unmarshaller
			 */
			void _prepare_next_receive();

			/**
			 * Wait for incoming message to be received in _rcv_msg
			 */
			void _wait();

		public:

			explicit Ipc_istream(Msgbuf_base *rcv_msg);

			~Ipc_istream();

			/**
			 * Read badge that was supplied with the message
			 */
			long badge() { return _long_at_idx(0); }

			/**
			 * Block for an incoming message filling the receive buffer
			 */
			Ipc_istream &operator >> (Ipc_istream_wait)
			{
				_wait();
				return *this;
			}

			/**
			 * Read values from receive buffer
			 */
			template <typename T>
			Ipc_istream &operator >> (T &value)
			{
				_read_from_buf(value);
				return *this;
			}

			/**
			 * Read byte buffer from receive buffer
			 */
			Ipc_istream &operator >> (Buffer &b)
			{
				_read_bytebuf_from_buf(b);
				return *this;
			}
	};


	class Ipc_client: public Ipc_istream, public Ipc_ostream
	{
		protected:

			int _result;   /* result of most recent call */

			void _prepare_next_call();

			/**
			 * Send RPC message and wait for result
			 */
			void _call();

		public:

			/**
			 * Constructor
			 */
			Ipc_client(Capability &srv, Msgbuf_base *snd_msg,
			                            Msgbuf_base *rcv_msg);

			/**
			 * Operator that issues an IPC call
			 *
			 * \throw Ipc_error
			 * \throw Blocking_canceled
			 */
			Ipc_client &operator << (Ipc_client_call)
			{
				_call();
				_read_from_buf(_result);
				if (_result == ERR_INVALID_OBJECT)
					throw Ipc_error();
				return *this;
			}

			template <typename T>
			Ipc_client &operator << (T value)
			{
				_write_to_buf(value);
				return *this;
			}

			Ipc_client &operator << (Buffer b)
			{
				_write_buffer_to_buf(b);
				return *this;
			}

			template <typename T>
			Ipc_client &operator >> (T &value)
			{
				_read_from_buf(value);
				return *this;
			}

			Ipc_client &operator >> (Buffer &b)
			{
				_read_bytebuf_from_buf(b);
				return *this;
			}

			operator int ()
			{
				return _result;
			}
	};


	class Ipc_server : public Ipc_istream, public Ipc_ostream
	{
		protected:

			bool _reply_needed;   /* false for the first reply_wait */

			void _prepare_next_reply_wait();

			/**
			 * Send result of previous RPC request and wait for new one
			 */
			void _reply_wait();

		public:

			/**
			 * Constructor
			 */
			Ipc_server(Msgbuf_base *snd_msg, Msgbuf_base *rcv_msg);

			/**
			 * Reply current request and wait for a new one
			 */
			Ipc_server &operator >> (Ipc_server_reply_wait)
			{
				_reply_wait();
				return *this;
			}

			/**
			 * Set return value of server call
			 */
			void ret(int retval)
			{
				*reinterpret_cast<int *>(&_sndbuf[sizeof(umword_t)]) = retval;
			};

			template <typename T>
			Ipc_server &operator << (T value)
			{
				_write_to_buf(value);
				return *this;
			}

			template <typename T>
			Ipc_server &operator >> (T &value)
			{
				_read_from_buf(value);
				return *this;
			}
	};
}

#endif /* _INCLUDE__BASE__IPC_GENERIC_H_ */
